//
//  Top_VC.m
//  WorldOfFacts_V2
//
//  Created by Demjanko Denis on 21.11.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "Top_VC.h"
#import "DataBase.h"
#import "TopCell.h"
#import "SVPullToRefresh.h"
#import "Service.h"
#import "DetailFact_VC.h"

@implementation Top_VC

#pragma mark - init

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"Топ факты";
    }
    return self;
}

- (void)setNavTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        
        titleView.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f]; // Change to desired color
        
        self.navigationItem.titleView = titleView;
    }
    
    titleView.text = title;
    [titleView sizeToFit];
}

#pragma mark - View Life

- (void)viewDidLoad{
    [super viewDidLoad];    
    [self configureTable];
    [self registerNotifications];
    [self setNavTitle:@"Топ факты"];

    factsArray = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:@"factsArray_top"]];
    
    if(factsArray.count==0)
        [self refreshFacts];
}

-(void)configureTable{
    __unsafe_unretained id weakSelf = self;
    
    table.showsInfiniteScrolling = TRUE;
    table.showsPullToRefresh = TRUE;
    
    [table addPullToRefreshWithActionHandler:^{
        [weakSelf refreshFacts];
    }];

    if([[NSUserDefaults standardUserDefaults] objectForKey:@"top_update"])
        table.pullToRefreshView.lastUpdatedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"top_update"];
}

#pragma mark - service

-(void)refreshFacts{
    [[Service sharedManeger] getTopFacts:^(NSData *response, NSError *error) {
        table.pullToRefreshView.lastUpdatedDate = [NSDate date];
        [table.pullToRefreshView performSelector:@selector(stopAnimating) withObject:nil afterDelay:0];
        
        if(error){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
        }
        else{
            [factsArray removeAllObjects];
            
            NSMutableArray *return_facts = [NSMutableArray arrayWithArray:[response objectFromJSONData]];
            
            for (int i=0; i<return_facts.count; i++) {
                int f_id = [[[return_facts objectAtIndex:i] valueForKey:@"fact_id"] intValue];  
                int likes = [[[return_facts objectAtIndex:i] valueForKey:@"cnt"] intValue];
                
                BOOL available = [[DataBase sharedManeger] isFactAvailabe:f_id];
                
                if(available){
                    NSMutableDictionary *fact = [NSMutableDictionary dictionaryWithDictionary:[[DataBase sharedManeger]getMiniFact:f_id]];
                    [fact setValue:[NSString stringWithFormat:@"%d",likes] forKey:@"likes"];
                    [factsArray addObject:fact];
                }
                
                [[NSUserDefaults standardUserDefaults] setObject:factsArray forKey:@"factsArray_top"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            
            [table reloadData];
        } 
    }];
}

#pragma mark - notifications

-(void)registerNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangeTop:) name:@"CHANGE_TOP" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSetRead:) name:@"SET_READ" object:nil];
}

-(void)removeNotificatios{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CHANGE_TOP" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SET_READ" object:nil];
}

-(void)onChangeTop:(NSNotification*)notification{
    int likes = [[notification.object valueForKey:@"likes"] intValue];
    int f_number = [[notification.object valueForKey:@"f_number"] intValue];
    
    [[factsArray objectAtIndex:f_number] setValue:[NSString stringWithFormat:@"%d",likes] forKey:@"likes"];
    [table reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:f_number inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)onSetRead:(NSNotification*)notification{
    int fact_number = [notification.object intValue];
    
    [[factsArray objectAtIndex:fact_number] setValue:[NSNumber numberWithInt:1] forKey:@"is_read"];
    [table reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:fact_number inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return factsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    
    TopCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[TopCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];                        
    }
    
    [cell setFact:[factsArray objectAtIndex:indexPath.row]];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableArray *ids = [NSMutableArray array];
    
    for (int i=0; i<factsArray.count; i++) {
        [ids addObject:[NSNumber numberWithInt:[[[factsArray objectAtIndex:i] valueForKey:@"fact_id"] intValue]]];
    }
    
    DetailFact_VC *vc = [[DetailFact_VC alloc] initWithNibName:@"DetailFact_VC" bundle:nil];
    vc.fact_id = [[[factsArray objectAtIndex:indexPath.row] valueForKey:@"fact_id"] intValue];
    vc.fact_number = indexPath.row;
    vc.fact_type = 0;
    vc.category_id = 0;
    vc.fact_mode = 3;
    vc.factIds = [[NSMutableArray alloc] initWithArray:ids];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - Memory Management

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    factsArray = nil;  
    [self removeNotificatios];
}

@end

